package com.sz.web.common.filter;

import com.alibaba.fastjson.JSON;
import com.sz.web.common.enums.SessionKey;
import com.sz.web.util.ReturnUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/**
 * 登录过滤
 */
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object accountUser = request.getSession().getAttribute(SessionKey.ACCOUNTINFO.getStrKey());
        if (accountUser == null) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            OutputStream out = null;
            try {
                out = response.getOutputStream();
                out.write(JSON.toJSONString(ReturnUtil.fail("请登录")).getBytes("UTF-8"));
                response.sendRedirect("/web");
                return false;

            } catch (Exception e) {

                throw new RuntimeException(e);

            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } else {
            return true;
        }
    }
}
